package com.wnhoo.smartfishtank.fishtank;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.wnhoo.smartfishtank.R;
import com.wnhoo.smartfishtank.api.LM_PlugAPIs;
import com.wnhoo.smartfishtank.api.data.DataPlug;
import com.wnhoo.smartfishtank.api.data.LM_DataReceive;
import com.wnhoo.smartfishtank.api.data.LM_DataSend;
import com.wnhoo.smartfishtank.api.data.LM_DataStatus;
import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.base.BaseActivity;
import com.wnhoo.smartfishtank.brodcast.NetWorkChangeBroadcastReceiver;
import com.wnhoo.smartfishtank.ui.UISwitchButton;
import com.wnhoo.smartfishtank.util.UIUtil;

import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.lang.Thread.sleep;

public class ThermostatActivity extends BaseActivity implements BaseActivity.InitHeaderListener,
        UISwitchButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener, View.OnClickListener {

    private int max_seek = 100;
    private SeekBar seek_bar_warm;
    private RelativeLayout thermostat_bg;
    public Drawable[] skin = new Drawable[3];
    public static TransitionDrawable[] localTransitionDrawable = new TransitionDrawable[3];
    private TextView thermostat_tv_newTemperature, thermostat_tv_warm;
    private Button thermostat_btn_add, thermostat_btn_subteact;
    private DataPlug mDataPlug;
    private int warmTemperture, newTemperture;
    private final String close = "0";
    private final String openOne = "1";
    private final String openTwo = "2";
    private final String isOpen = "-1";//查询状态
    private ThreadHttpReceive threadDeviceStatus;
    private ThreadsendReceive threadsendReceive;
    private boolean isThreadHttpReceive;
    private int value;//当前进度条选中的是那个开关状态
    private String thermostat_deviation;
    public static ThermostatActivity instance;
    private long exitTime;
    private boolean isTotalState = true;//当进行点击开关的时候，暂时不接收全状态数据，不然页面有时会连续跳转
    private boolean isFirst = true;
    private TextView ther_online_tv;
    private UISwitchButton seek_bar_warm1;
    private TextView ther_device_state;
    private RelativeLayout thermostat_State_show;//温控器状态显示
    private ImageView ther_error;//温控器错误图片显示
    private ImageView imageView1;//红色的水球
    private String sendControlTyoe;//准备发送的控制命令是
    private String sendTemperatureTyoe;//准备发送的水温命令是
    private boolean isSendControl;//是否发送控制命令
    private boolean isSendTemperature;//是否发送水温命令
    private ExecutorService exec;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thermostat);
        setOnInitListener(this);
        instance = this;
        initView();
        initData();
        seek_bar_warm = (SeekBar) findViewById(R.id.seek_bar_warm);
        seek_bar_warm.setOnSeekBarChangeListener(this);
        seek_bar_warm.setMax(max_seek);

        this.onStopTrackingTouch(seek_bar_warm);
    }

    private void initData() {
        exec = Executors.newSingleThreadExecutor();
        warmTemperture = 27;
        newTemperture = 27;
        mDataPlug = LMAPP.dataPlug;
        mDataPlug.setOnline("1");
        startHttpStatus();
        IntentFilter intentFilter = new IntentFilter(NetWorkChangeBroadcastReceiver.NETWORKCHANGE);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean isNetWork = intent.getBooleanExtra("isNetWork", true);
                if (isNetWork) {
                    ther_online_tv.setText(getStringXml(R.string.device_connect));
                } else {
                    ther_online_tv.setText(getStringXml(R.string.network_disconnect));
                }
            }
        }, intentFilter);
        startPeriodicTransmit();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopHttpStatus();
//        startHttpStatus();
    }

    @Override
    public void initView() {
        super.initView();
        // 得到TextView控件对象
        thermostat_tv_newTemperature = (TextView) findViewById(R.id.thermostat_tv_newTemperature);
        thermostat_tv_warm = (TextView) findViewById(R.id.thermostat_tv_warm);
        thermostat_btn_add = (Button) findViewById(R.id.thermostat_btn_add);
        thermostat_btn_subteact = (Button) findViewById(R.id.thermostat_btn_subteact);
        thermostat_bg = (RelativeLayout) findViewById(R.id.thermostat_bg);
        thermostat_State_show = (RelativeLayout) findViewById(R.id.linearLayout);
        ther_error = (ImageView) findViewById(R.id.ther_error);
        ther_online_tv = (TextView) findViewById(R.id.ther_online_tv);
        ther_device_state = (TextView) findViewById(R.id.ther_device_state);
        seek_bar_warm1 = (UISwitchButton) findViewById(R.id.seek_bar_warm1);
        imageView1 = (ImageView) findViewById(R.id.imageView1);
        seek_bar_warm1.setOnCheckedChangeListener(this);
        thermostat_btn_add.setOnClickListener(this);
        thermostat_btn_subteact.setOnClickListener(this);
// 将字体文件保存在assets/fonts/目录下，www.linuxidc.com创建Typeface对象
        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/familiar.ttf");
//        Typeface tf = Typeface.createFromFile("@assets/fonts/familiar.ttf");
// 应用字体
        thermostat_tv_newTemperature.setTypeface(typeFace);
//        getPaint().setFakeBoldText(true);
        skin[0] = new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.temperature_bg_black));
        skin[1] = new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.thermostat_bg1));
        skin[2] = new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.temperature_bg_red));
        localTransitionDrawable[0] = new TransitionDrawable(new Drawable[]{new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.common_bg)), skin[0]});
        localTransitionDrawable[1] = new TransitionDrawable(new Drawable[]{new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.common_bg)), skin[1]});
        localTransitionDrawable[2] = new TransitionDrawable(new Drawable[]{new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.common_bg)), skin[2]});

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.thermostat_btn_add:
                if (warmTemperture >= 17 && warmTemperture < 35) {
                    warmTemperture += 1;
                }
                thermostat_tv_warm.setText(warmTemperture + "℃");

                sendControlTemperatureHttp(String.valueOf(warmTemperture));
                isTotalState = false;
//                sendTemperatureSwitch();
                break;
            case R.id.thermostat_btn_subteact:
                if (warmTemperture > 17 && warmTemperture <= 35) {
                    warmTemperture -= 1;
                }
                thermostat_tv_warm.setText(warmTemperture + "℃");
                sendControlTemperatureHttp(String.valueOf(warmTemperture));
                isTotalState = false;
//                sendTemperatureSwitch();
                break;
        }
    }

//    /**
//     * 设置温度可开关
//     */
//    private void sendTemperatureSwitch() {
////        sendControlTemperatureHttp(String.valueOf(warmTemperture));
//        switch (value) {
//            case 0:
//                sendControlPlugHttp(close);
//                break;
//            case 50:
//                sendControlPlugHttp(openOne);
//                break;
//            case 100:
//                sendControlPlugHttp(openTwo);
//                break;
//        }
//    }

    @Override
    public void OnSetTitle(TextView t) {
        t.setText(getStringXml(R.string.thermostat));
    }

    @Override
    public void OnSetLeftView(Button btn) {
        btn.setVisibility(View.VISIBLE);
        btn.setBackgroundResource(R.drawable.light_back_selector);
    }

    @Override
    public void OnSetRightView(Button btn) {
        btn.setVisibility(View.VISIBLE);
        btn.setBackgroundResource(R.drawable.light_set_selector);
    }

    @Override
    public void OnSetLeftOnclick(View view) {
    }

    @Override
    public void OnSetRightOnclick(View view) {
        Intent intent = new Intent(ThermostatActivity.this, Ther_SettingActivity.class);
        intent.putExtra("thermostat_deviation", thermostat_deviation);
        startActivity(intent);
    }

    @Override
    public void onSetbackground(View view) {
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (isFirst) {
            return;
        }
        value = seekBar.getProgress();
        if (value < 25) {
            value = 0;
            seekBar.setProgress(0);
            setBackground(localTransitionDrawable[0]);
            localTransitionDrawable[0].startTransition(1000);
            sendControlPlugHttp(close);
            isTotalState = false;
//            sendTemperatureSwitch();
        } else if (value >= 25 && value < 50 || value >= 50 && value < 75) {
            value = 50;
            seekBar.setProgress(50);
            setBackground(localTransitionDrawable[1]);
            localTransitionDrawable[1].startTransition(1000);
            sendControlPlugHttp(openOne);
            isTotalState = false;
//            sendTemperatureSwitch();
        } else if (value >= 75 && value <= 100) {
            value = 100;
            seekBar.setProgress(100);
            setBackground(localTransitionDrawable[2]);
            localTransitionDrawable[2].startTransition(1000);
            sendControlPlugHttp(openTwo);
            isTotalState = false;
//            sendTemperatureSwitch();
        }
    }

    //控制温控器开关状态
    private void sendControl(String state) {
//        if (LMAPP.dataPlug.getFull_status().startsWith("1")) {
        sendControlPlugHttp(state);
        LMAPP.dataPlug.setFull_status(state + ",700");
//        }
    }

    private void startPeriodicTransmit() {
        exec.execute(sendRunable);
    }
    //控制之前默认发送的控制命令，请求最新状态
    public void sendControlPlug(String type) {
        sendControlTyoe = type;
        isSendControl = true;
    }
    //控制开关
    public void sendControlPlugHttp(String type) {
        sendControlTyoe = type;
        isSendControl = true;
    }
    //控制水温
    public void sendControlTemperatureHttp(String type) {
        isSendTemperature = true;
    }


    public Runnable sendRunable = new Runnable() {
        @Override
        public void run() {
            while (true){
                try {
                    if(isSendControl){
                        try {
                            Log.i(TAG, "正在发送命令的方法"+sendControlTyoe);
                            LM_DataSend dataSend = LM_PlugAPIs.requestSendControl(true, LMAPP.dataPlug.getId(), sendControlTyoe, LMAPP.token_default);
                            Log.i(TAG, "正在发送命令的方法回馈"+dataSend);
                            sendMessageToUI(MSG_HTTP_SEND_RESULT, dataSend);
                            isSendControl = false;
                            Log.i(TAG, dataSend.toString());
                        } catch (Exception e) {
                            //MyLog.exception(e);
                            sendMessageToUI(MSG_HTTP_SEND_EXCEPTION, e);
                        }
                    }
                    if(isSendTemperature){
                        isSendTemperature = false;
                        try {
                            Log.i(TAG, "正在发送温度命令的方法"+warmTemperture);
                            LM_DataSend dataSend = LM_PlugAPIs.requestSendTemperature(true, LMAPP.dataPlug.getId(), String.valueOf(warmTemperture), LMAPP.token_default);
                            sendMessageToUI(MSG_HTTP_SEND_RESULT, dataSend);
                            Log.i(TAG, "sendControlTemperatureHttp" + dataSend.toString());
                        } catch (Exception e) {
                            //MyLog.exception(e);
                            sendMessageToUI(MSG_HTTP_SEND_EXCEPTION, e);
                        }
                    }
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    //控制水温偏差
    public void sendControlDeviationHttp(final String type) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {

                    LM_DataSend dataSend = LM_PlugAPIs.requestSendTemperatureDifference(true, LMAPP.dataPlug.getId(), type, LMAPP.token_default);
                    //DataSend dataSend = PlugAPIs.requestSendControl(true, dataPlug.getId(), type,plugActivity.getToken() );
                    sendMessageToUI(MSG_HTTP_SEND_RESULT, dataSend);
                    ////MyLog.s(tag,version.toString());
                } catch (Exception e) {
                    //MyLog.exception(e);
                    sendMessageToUI(MSG_HTTP_SEND_EXCEPTION, e);
                }
            }
        }.start();
    }

    //Http
    private final static int MSG_HTTP_SEND_RESULT = 1;
    private final static int MSG_HTTP_SEND_EXCEPTION = 2;
    private final static int MSG_HTTP_RECEIVE_FULL_STATUS = 3;
    private final static int MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION = 4;
    private final static int MSG_HTTP_ONLINE_STATUS = 5;
    private final static int MSG_HTTP_ONLINE_STATUS_EXCEPTION = 6;

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_HTTP_SEND_RESULT:
                    //handlerSendResult(msg);
                    break;
                case MSG_HTTP_SEND_EXCEPTION:

                    break;
                case MSG_HTTP_RECEIVE_FULL_STATUS:
                    //设备返回它的全状态
                    handlerReceiveFullStatus(msg);
                    break;
                case MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION:
                    //if(isDebug)debug_status.setText("Debug:"+msg.obj.toString());
                    break;
                case MSG_HTTP_ONLINE_STATUS_EXCEPTION:
                    //异常应该让状态变为离线
                    //setOfflineTextView();
                    break;
                case MSG_HTTP_ONLINE_STATUS:
                    handlerOnlineStatus(msg);
                    break;
                default:

                    break;
            }
        }
    };

    public void sendMessageToUI(int what, Object obj) {

        Message message = Message.obtain();
        message.what = what;
        message.obj = obj;
        handler.sendMessage(message);
    }

    /**
     * 处理在线状态请求结果
     *
     * @param msg
     */
    public void handlerOnlineStatus(Message msg) {
        LM_DataStatus dataReceive = (LM_DataStatus) msg.obj;
        Log.d(TAG, "online=");
        if (dataReceive == null) {
            Log.d(TAG, "online=kong");
            return;
        }
        Log.d(TAG, "online=" + dataReceive.getOnline());

        if (LMAPP.dataPlug != null) LMAPP.dataPlug.setOnline(dataReceive.getOnline());
        if ("1".equals(dataReceive.getOnline())) {
            ther_online_tv.setText(getStringXml(R.string.online));
        } else if ("0".equals(dataReceive.getOnline())) {
            ther_online_tv.setText(getStringXml(R.string.offline));
        } else {
            ther_online_tv.setText(getStringXml(R.string.online));
//            MyLog.s(tag,"Debug:没有解析出结果是离线还是在线，内容："+dataReceive.getOnline());
        }
    }

    public void handlerReceiveFullStatus(Message msg) {
        if (!isTotalState) {
            isTotalState = true;
            return;
        }
        isFirst = false;
        //MyLog.TT("TEST",msg.obj.toString());
        LM_DataReceive dataReceive = (LM_DataReceive) msg.obj;
        if (dataReceive == null) {
            Log.i("return", "dataReceive==null");
            return;
        }
        Log.i("return", "dataReceive" + dataReceive.toString());

        if (dataReceive.getValue() == null || dataReceive.getValue().length() < 6) {
            return;
        } else {
            String[] totalState = dataReceive.getValue().split(",");
            Log.i(TAG, "totalState" + totalState[0]);
            switch (totalState[0]) {
                case "0":
                    if (seek_bar_warm1.isChecked()) {
                        setBackground(localTransitionDrawable[0]);
                        localTransitionDrawable[0].startTransition(1000);
                    }
                    seek_bar_warm1.setChecked(false);
                    break;
                case "1":
                    if (!seek_bar_warm1.isChecked()) {
                        setBackground(localTransitionDrawable[1]);
                        localTransitionDrawable[1].startTransition(1000);
                    }
                    seek_bar_warm1.setChecked(true);
                    break;
            }
            switch (totalState[4]) {
                case "0":
                    ther_device_state.setText(getStringXml(R.string.heated));
                    imageView1.setVisibility(View.GONE);
                    Log.i(TAG, "Integer.parseInt(totalState[2])+未加热");
//                    if (!seek_bar_warm1.isChecked()) {

//                    }
                    break;
                case "1":
                    ther_device_state.setText(getStringXml(R.string.heating));
                    imageView1.setVisibility(View.VISIBLE);
                    Log.i(TAG, "Integer.parseInt(totalState[2])+正在加热");
//
                    break;
            }
            thermostat_tv_warm.setText(totalState[1] + "℃");
            warmTemperture = Integer.parseInt(totalState[1]);
            Log.i(TAG, "Integer.parseInt(totalState[2])" + Integer.parseInt(totalState[2]));
            if (Integer.parseInt(totalState[2]) <= 35) {
                Log.i(TAG, "Integer.parseInt(totalState[2])<35");
                ther_error.setVisibility(View.GONE);
                thermostat_State_show.setVisibility(View.VISIBLE);
                thermostat_tv_newTemperature.setText(totalState[2] + "");
            } else {
                Log.i(TAG, "Integer.parseInt(totalState[2])>35");
                ther_error.setVisibility(View.VISIBLE);
                thermostat_State_show.setVisibility(View.GONE);
                if(isZh(this)){
                    ther_error.setImageResource(R.drawable.overheat_icon);
                }else{
                    ther_error.setImageResource(R.drawable.overheat_icon_en);
                }
                return;
            }
            if (Integer.parseInt(totalState[5]) == 1) {
                ther_error.setVisibility(View.VISIBLE);
                thermostat_State_show.setVisibility(View.GONE);
                if(isZh(this)){
                    ther_error.setImageResource(R.drawable.hydropenia_icon);
                }else{
                    ther_error.setImageResource(R.drawable.hydropenia_icon_en);
                }
            } else {
                ther_error.setVisibility(View.GONE);
                thermostat_State_show.setVisibility(View.VISIBLE);
            }
        }
    }
    public static boolean isZh(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            setBackground(localTransitionDrawable[1]);
            localTransitionDrawable[1].startTransition(1000);
            sendControlPlugHttp(openOne);
            isTotalState = false;
        } else {
            setBackground(localTransitionDrawable[0]);
            localTransitionDrawable[0].startTransition(1000);
            sendControlPlugHttp(close);
            isTotalState = false;
        }
    }

//    /**
//     * 不断请求设备当前状态温度的的线程
//     */
//    private class ThreadHttpReceive extends Thread {
//        @Override
//        public void run() {
//            // TODO Auto-generated method stub
//
//            while (isThreadHttpReceive) {
//                try {
//                    if (LMAPP.dataPlug != null) {
//                        LM_DataStatus data_status = LM_PlugAPIs.requestOnlineStatus(false, LMAPP.dataPlug.getId(), LMAPP.getAccessToken());
//                        Log.i("i", "=====data_status" + data_status);
//                        sendMessageToUI(MSG_HTTP_RECEIVE_FULL_STATUS, data_status);
//                        sendMessageToUI(MSG_HTTP_ONLINE_STATUS, data_status);
//                    }
//                } catch (Exception e) {
//                    //MyLog.exception(e);
//                    sendMessageToUI(MSG_HTTP_ONLINE_STATUS_EXCEPTION, e);
//                    sendMessageToUI(MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION, e);
//                } finally {
//                    //睡眠必须要执行到
//                    try {
//                        sleep(3 * 1000);
//                    } catch (Exception e1) {
//                    }
//                }
//            }
//            super.run();
//        }
//    }
    /**
     * 不断请求设备当前状态的的线程。莫名的要求  为了适应设备的bug   发送命令3
     */
    private class ThreadsendReceive extends Thread {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (isThreadHttpReceive) {
                try {
                    if (LMAPP.dataPlug != null) {
                        LM_DataSend dataSend = LM_PlugAPIs.requestSendTemperatureDifference(true, LMAPP.dataPlug.getId(),"3", LMAPP.token_default);
                        Log.i("i", "=====data_status+发送的命令是3");
//                        Log.i("i", "=====data_status" + data_status_online);
//                        sendMessageToUI(MSG_HTTP_SEND_RESULT, dataSend);
                        sleep(60 * 1000);
                    }
                } catch (Exception e) {
                    //MyLog.exception(e);
                    sendMessageToUI(MSG_HTTP_SEND_RESULT, e);
                } finally {
//                    睡眠必须要执行到
                    try {
                    } catch (Exception e1) {
                    }
                }
            }
            super.run();
        }
    }
    /**
     * 不断请求设备当前状态温度的的线程
     */
    private class ThreadHttpReceive extends Thread {
        @Override
        public void run() {
            // TODO Auto-generated method stub

            while (isThreadHttpReceive) {
                try {
                    sleep(3 * 1000);
                    if (LMAPP.dataPlug != null) {
                        LM_DataReceive data_status = LM_PlugAPIs.requestReceiveData(false, LMAPP.dataPlug.getId(), "S14", "1", LMAPP.getAccessToken());
                        LM_DataStatus data_status_online = LM_PlugAPIs.requestOnlineStatus(true, LMAPP.dataPlug.getId(), LMAPP.getAccessToken());
//                        Log.i("i", "=====data_status" + data_status);
//                        Log.i("i", "=====data_status" + data_status_online);
                        sendMessageToUI(MSG_HTTP_RECEIVE_FULL_STATUS, data_status);
                        sendMessageToUI(MSG_HTTP_ONLINE_STATUS, data_status_online);
                    }
                } catch (Exception e) {
                    //MyLog.exception(e);
                    sendMessageToUI(MSG_HTTP_ONLINE_STATUS_EXCEPTION, e);
                    sendMessageToUI(MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION, e);
                } finally {
//                    睡眠必须要执行到
                    try {
                    } catch (Exception e1) {
                    }
                }
            }
            super.run();
        }
    }

    public void startHttpStatus() {

        if (threadDeviceStatus == null) {
            //MyLog.i(tag,"startHttpStatus");
            isThreadHttpReceive = true;
            threadDeviceStatus = new ThreadHttpReceive();
            threadsendReceive = new ThreadsendReceive();
            threadDeviceStatus.start();
            threadsendReceive.start();
        }
    }

    public void stopHttpStatus() {
        try {
            isThreadHttpReceive = false;
            if (threadDeviceStatus != null) {
                threadDeviceStatus.interrupt();
                threadDeviceStatus = null;
                //MyLog.i(tag,"stopHttpStatus");
            } else {
                //MyLog.e(tag, "HttpStatus is stop.");
            }
            if(threadsendReceive!=null){
                threadsendReceive.interrupt();
                threadsendReceive = null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            //MyLog.i(tag,"stopHttpStatus Exception:"+e.toString());
            //MyLog.exception(e);
        }
    }
}
